package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.PropertiesUrlUtil;
import cc.linker.steplink.crm.dao.CustomerDao;
import cc.linker.steplink.crm.dao.LevelDao;
import cc.linker.steplink.crm.dao.ScoreLogDao;
import cc.linker.steplink.crm.dao.TemplateMessageDao;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信模板消息
 *
 * @author wuyue
 */
@Slf4j
@Component
public class WxTemplateMsgTask {

    @Autowired
    private MallService mallService;
    @Autowired
    private SystemProperties systemProperties;

    private static Map<String, String> jsonPostMap = new HashMap<>();

    static {
        jsonPostMap.put("Content-Type", "application/json;charset=UTF-8");
    }

    @Autowired
    private ScoreLogDao scoreLogDao;
    @Autowired
    private HttpService httpService;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private TemplateMessageDao templateMessageDao;
    @Autowired
    private LevelDao levelDao;

    /**
     * 积分消息+等级消息
     */
    @RedisLock(value = "WxTemplateMsgTask")
    @Scheduled(cron = "10 */3 * * * ?")
    public void sendMsg() throws IOException, URISyntaxException {
//        LOGGER.info("微信模板消息开始啦~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        // 模板表
        List<Map<String, Object>> list = templateMessageDao.listAllTemplates();
        for (Map<String, Object> map : list) {
            String orgId = (String) map.get("orgId");
            // 模板id
            String templateId = (String) map.get("templateId");
            // 模板类型 1积分变动提醒 2等级变动提醒
            String templateType = (String) map.get("templateType");
            // 推送类型 1按照触发推送 2按照固定时间推送
            String pushType = (String) map.get("pushType");
            // 打开时间
            String lastOpenTime = map.get("lastOpenTime").toString();
            // 推送时间 pushType=2才有
            String pushTime = null;
            if (map.get("pushTime") != null) {
                pushTime = map.get("pushTime").toString();
            }
            if ("1".equals(templateType) && "1".equals(pushType)) {
                // 积分触发推送
                score(orgId, templateId, lastOpenTime, 1);
            } else if ("1".equals(templateType) && "2".equals(pushType)) {
                if (pushTime == null) {
                    LOGGER.info("推送时间不正确");
                    continue;
                }
                // 积分定时推送
                LocalTime localTime = LocalTime.now();
                LocalTime parse = LocalTime.parse(pushTime);
                long between = ChronoUnit.MINUTES.between(parse, localTime);
                if (between >= 0 && between < 5) {
                    score(orgId, templateId, lastOpenTime, 2);
                }
            } else if ("2".equals(templateType) && "1".equals(pushType)) {
                // 等级触发推送
                level(orgId, templateId, lastOpenTime, 1);
            } else if ("2".equals(templateType) && "2".equals(pushType)) {
                if (pushTime == null) {
                    LOGGER.info("推送时间不正确");
                    continue;
                }
                // 等级定时推送
                LocalTime localTime = LocalTime.now();
                LocalTime parse = LocalTime.parse(pushTime);
                long between = ChronoUnit.MINUTES.between(parse, localTime);
                if (between >= 0 && between < 5) {
                    level(orgId, templateId, lastOpenTime, 2);
                }
            } else {
                LOGGER.info("推送类型不正确");
            }
        }
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        LOGGER.info("微信模板消息结束啦~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }

    /**
     * 积分消息
     *
     * @param orgId      机构id
     * @param templateId 模板id
     * @param type       类型
     * @throws IOException
     * @throws URISyntaxException
     */
    private void score(String orgId, String templateId, String lastOpenTime, int type) throws IOException, URISyntaxException {
        List<Map<String, Object>> scoreLog;
        if (type == 1) {
            scoreLog = scoreLogDao.listScoreLogByOrgIdWhereNotScored(orgId, lastOpenTime);
        } else if (type == 2) {
            scoreLog = scoreLogDao.listScoreLogByOrgIdWhereNotScoredSum(orgId, lastOpenTime);
        } else {
            return;
        }
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("action", "sendWxMessageStep");
        for (Map<String, Object> log : scoreLog) {
            String token = (String) log.get("token");
            String openId = (String) log.get("openId");
            String customerId = (String) log.get("customerId");
            String scoreLogId = (String) log.get("scoreLogId");
            Long customerScore = (Long) log.get("customerScore");
            Long scoreValue = Long.valueOf(log.get("scoreValue").toString());
            if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(openId)) {
                // 积分变动
                requestMap.put("token", token);
                requestMap.put("openid", openId);
                requestMap.put("template_id", templateId);
                String scrmWebUrl = systemProperties.getAcsScrmWebUrl();
                String url = PropertiesUrlUtil.format(scrmWebUrl)
                        + Constants.URI_H5_USER_CENTER + "?goto=credit";
                requestMap.put("url", PropertiesUrlUtil.format(systemProperties.getScrmUrl())
                        + Constants.URI_H5_LOGIN + "?token=" + token
                        + "&m=" + URLEncoder.encode(url, "utf-8"));
                requestMap.put("first", "尊敬的会员，你的积分发生了变动");
                requestMap.put("keyword1", levelDao.getLevelNameByScore(orgId, customerScore));
                requestMap.put("keyword2", customerScore);
                requestMap.put("keyword3", scoreValue + "积分");
                requestMap.put("remark", "点击查看详情");
                String res = httpService.doPost(systemProperties.getWxpushurl(), JSON.serialize(requestMap), jsonPostMap);
                Map parse = (Map) JSON.parse(res);
                LOGGER.info("WxTemplateMsgTask_score_parse = " + parse);
            } else {
                LOGGER.info("token或openid获取失败");
            }
            // 修改log状态
            if (type == 1) {
                scoreLogDao.updateSendStateByPrimaryKeyAfterScore(scoreLogId);
            } else {
                scoreLogDao.updateSendStateByPrimaryKeyAfterScoreGroup(scoreLogId);
            }
        }
    }

    /**
     * 等级消息
     *
     * @param orgId      机构id
     * @param templateId 模板id
     * @param type       类型
     * @throws IOException
     * @throws URISyntaxException
     */
    private void level(String orgId, String templateId, String lastOpenTime, int type) throws IOException, URISyntaxException {
        List<Map<String, Object>> scoreLog;
        if (type == 1) {
            scoreLog = scoreLogDao.listScoreLogByOrgIdWhereNotLeveled(orgId, lastOpenTime);
        } else if (type == 2) {
            scoreLog = scoreLogDao.listScoreLogByOrgIdWhereNotLeveledSum(orgId, lastOpenTime);
        } else {
            return;
        }
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("action", "sendWxMessageStep");
        for (Map<String, Object> log : scoreLog) {
            String token = (String) log.get("token");
            String openId = (String) log.get("openId");
            String customerId = (String) log.get("customerId");
            String scoreLogId = (String) log.get("scoreLogId");
            // 用户当前积分
            //Long customerScore = (Long) log.get("customerScore");
            // 用户当前成长积分
            Long customerScore = (Long) log.get("customerGrowthScore");
            // 用户积分变化
//            Long scoreValue = (Long) log.get("scoreValue");
            Long scoreValue = Long.valueOf(log.get("scoreValue").toString());
            if (scoreValue <= 0) {
                continue;
            }
            // 当前-变化=之前
            long i = customerScore - scoreValue;
            String levelNameNow = levelDao.getLevelNameByScore(orgId, customerScore);
            String levelNameBefore = levelDao.getLevelNameByScore(orgId, i);
            if (!StringUtils.isEmpty(levelNameNow) && !levelNameNow.equals(levelNameBefore)) {
                // 如果前后等级名不同
                if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(openId)) {
                    requestMap.put("token", token);
                    requestMap.put("openid", openId);
                    requestMap.put("template_id", templateId);
                    String scrmWebUrl = systemProperties.getAcsScrmWebUrl();
                    String url = PropertiesUrlUtil.format(scrmWebUrl)
                            + Constants.URI_H5_USER_CENTER + "?goto=credit";
                    requestMap.put("url", PropertiesUrlUtil.format(systemProperties.getScrmUrl())
                            + Constants.URI_H5_LOGIN + "?token=" + token
                            + "&m=" + URLEncoder.encode(url, "utf-8"));
                    requestMap.put("first", "尊敬的会员，你的会员等级提高啦");
                    requestMap.put("keyword1", StringUtils.isEmpty(levelNameBefore) ? "无" : levelNameBefore);
                    requestMap.put("keyword2", levelNameNow);
                    requestMap.put("keyword3", "无");
                    String levelGifts = levelDao.getLevelGiftsByScore(orgId, customerScore);
                    requestMap.put("keyword4", levelGifts);
                    requestMap.put("remark", "点击查看详情");
                    String res = httpService.doPost(systemProperties.getWxpushurl(), JSON.serialize(requestMap), jsonPostMap);
                    Map parse = (Map) JSON.parse(res);
                    LOGGER.info("WxTemplateMsgTask_level_parse = " + parse);
                } else {
                    LOGGER.info("token或openid获取失败");
                }
            }
            // 修改log状态
            if (type == 1) {
                scoreLogDao.updateSendStateByPrimaryKeyAfterLevel(scoreLogId);
            } else {
                scoreLogDao.updateSendStateByPrimaryKeyAfterLevelGroup(scoreLogId);
            }
        }
    }
}
